<script setup lang="tsx">
defineOptions({
  name: "pmTaskEditNotes"
});

import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { PxMessage } from "px-ui";
import { queryFabPmDetail, createFabPMNotes, editFabPMNotes, deleteFabPMNotes } from "@/api/modules/fab";
import { Delete, EditPen, CircleCheck } from "@px-ui/icons-vue";
import { useMessageBox } from "@/hooks/useCommon";
import { useRouterStoreHook } from "@/store/modules/router";
import ReTextTooltip from "@/components/ReTextTooltip";

const routerStore = useRouterStoreHook();

const props = withDefaults(defineProps<{ jobNo: string }>(), { jobNo: "" });

const className = routerStore.getClassName;

const userId = ref<string>("");
const dialogVisible = defineModel({ type: Boolean, default: false });
const detailData = ref<Record<string, any> | null>(null);
const notes = ref<Array<any>>([]);
const isCreate = ref<boolean>(false);
const listLoading = ref<boolean>(false);
const loading = ref<boolean>(false);
const isEditStatus = ref<boolean>(false);

const createRuleFormRef = ref<FormInstance>();
const createNotsForm = reactive<{ message: string }>({
  message: ""
});
const createNotsRules = reactive<FormRules<{ message: string }>>({
  message: [{ required: true, message: "请输入评论", trigger: "blur" }]
});

const isShowList = computed(() => !!notes.value?.length);
const isShowBtn = computed(() => notes.value?.length && !isCreate.value);
const isShowInput = computed(() => !notes.value?.length || isCreate.value);

const editHandler = (item: any) => {
  item.edit = true;
  isEditStatus.value = true;
};

const editSaveHandler = async (item: any) => {
  const { id = "", message = "" } = item;
  const { jobNo: pmNo = "" } = detailData.value;
  // pm类型，是机台pm还是设备pm: EQP,DEVICE
  const pmType = "EQP";
  // 	是plan还是job: PLAN,JOB
  const planJobType = "JOB";
  const commentatorBy = userId.value;
  const params = { id, pmNo, pmType, planJobType, message, commentatorBy };
  await editFabPMNotes(params);
  item.edit = false;
  await init(true);
  item.edit = false;
  isEditStatus.value = false;
};

const deleteHandler = async (item: any) => {
  const msg = `确定删除这条评论吗？`;
  useMessageBox("delete", msg, async () => {
    const { id } = item;
    const ids = [id];
    await deleteFabPMNotes({ ids });
    await init(true);
    PxMessage.success("删除成功！");
  });
};

const cancelHandler = () => {
  isCreate.value = false;
  if (!notes.value?.length) {
    dialogVisible.value = false;
  }
};

const submitHandler = async () => {
  if (!createRuleFormRef.value) return;
  await createRuleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const { jobNo: pmNo = "" } = detailData.value;
      const { message } = createNotsForm;
      // pm类型，是机台pm还是设备pm: EQP,DEVICE
      const pmType = "EQP";
      // 	是plan还是job: PLAN,JOB
      const planJobType = "JOB";
      const commentatorBy = userId.value;
      const params = { pmNo, pmType, planJobType, message, commentatorBy };
      await createFabPMNotes(params, () => {
        loading.value = false;
      });
      await init(true);
      loading.value = false;
      createNotsForm.message = "";
    } else {
      console.error("error submit!", fields);
    }
  });
};

const init = async (flag: boolean = false) => {
  const userInfo = localStorage.getItem("userInfo");
  const { userId: userId_ = null } = JSON.parse(userInfo);
  userId.value = userId_?.toString();
  !flag && (notes.value = []);
  const { jobNo } = props;
  const params = { jobNo };
  listLoading.value = true;
  const res = await queryFabPmDetail(params, () => {
    listLoading.value = false;
  });
  listLoading.value = false;
  detailData.value = res;
  if (!res) return;
  notes.value = res.notes;
  isCreate.value = !notes.value.length;
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <px-dialog v-model="dialogVisible" width="800px" title="PM情况记录" destroy-on-close>
    <div v-loading="listLoading" class="pm-task-edit-notes">
      <px-scrollbar v-if="isShowList" class="notes-list" max-height="300px">
        <div v-for="item in notes" :key="item.id" class="notes-item">
          <div class="notes-item-content">
            <px-input
              v-if="item.edit"
              v-model.trim="item.message"
              class="notes-item-content-input"
              :rows="2"
              type="textarea"
              maxlength="1000"
              show-word-limit
              placeholder="请输入评论"
            />
            <div v-else class="notes-item-content-text">{{ item.message }}</div>
          </div>
          <div class="notes-item-bottom">
            <div class="notes-item-bottom-left">
              <div class="notes-date">{{ item?.commentatorTime }}</div>
              <div class="notes-account">{{ item?.commentatorByName }}</div>
              <div class="notes-role">
                <ReTextTooltip :content="item?.commentatorRole" />
              </div>
            </div>
            <div class="notes-item-bottom-right">
              <px-button
                v-if="item.edit"
                type="primary"
                size="large"
                :icon="CircleCheck"
                text
                plain
                :disabled="(item.commentatorBy !== userId && !!className) || !item.message"
                @click="editSaveHandler(item)"
              />
              <px-button
                v-else
                type="primary"
                size="large"
                :icon="EditPen"
                text
                plain
                :disabled="(item.commentatorBy !== userId && !!className) || isEditStatus"
                @click="editHandler(item)"
              />
              <px-button
                type="danger"
                size="large"
                :icon="Delete"
                text
                plain
                :disabled="(item.commentatorBy !== userId && !!className) || !item.message"
                @click="deleteHandler(item)"
              />
            </div>
          </div>
        </div>
      </px-scrollbar>
      <div v-if="isShowBtn" class="notes-btn">
        <px-button type="primary" plain @click="isCreate = true">新增记录</px-button>
      </div>
      <div v-if="isShowInput" v-loading="loading" class="notes-create">
        <px-form ref="createRuleFormRef" :model="createNotsForm" :rules="createNotsRules" label-width="0">
          <px-form-item prop="message">
            <px-input
              v-model.trim="createNotsForm.message"
              class="notes-create-input"
              :rows="3"
              type="textarea"
              maxlength="1000"
              show-word-limit
              placeholder="请输入评论"
            />
          </px-form-item>
        </px-form>
      </div>
    </div>
    <template v-if="isShowInput" #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" :disabled="!detailData" :loading="loading" @click="submitHandler">确定</px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
.pm-task-edit-notes {
  .notes-list {
    box-sizing: border-box;
    padding-right: 24px;

    .notes-item {
      margin-bottom: 20px;

      .notes-item-content {
        padding-bottom: 12px;
        border-bottom: 1px solid #e2e2e2;

        .notes-item-content-text {
          color: #333;
        }
        // .notes-item-content-input {
        // }
      }

      .notes-item-bottom {
        display: flex;
        flex-wrap: nowrap;
        gap: 24px;
        align-items: center;
        justify-content: space-between;

        .notes-item-bottom-left {
          display: flex;
          flex: 1;
          gap: 24px;
          align-items: center;
          width: 0;

          .notes-date {
            width: 160px;
          }

          .notes-account {
            width: 80px;
          }

          .notes-role {
            flex: 1;
            width: 0;
          }
        }

        .notes-item-bottom-right {
          display: flex;
          gap: 24px;
          align-items: center;
          width: fit-content;

          .px-button {
            padding: 12px 0;
            margin-left: 0;
            font-size: 20px;
          }
        }
      }
    }
  }

  .notes-btn {
    margin-top: 24px;
  }

  .notes-create {
    margin-top: 24px;
    // .notes-create-input {
    // }
  }
}
</style>
